package com.example.meijun.pantest;

import android.app.Notification;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.interfaces.RSAKey;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;


/**
 * Instrumentation test, which will execute on an Android device.
 *
 * @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
 */
public class Test {
    private static final String TAG = "ExampleInstrumentedTest";
  static   String baseUrl = "http://192.168.248.220:9080/pansoftdfs/";
    String uploadUrl = "files/file/upload";
    String addUrl = "files/dir/add";
    String queryUrl = "files/dir/66661/nextlevel/query";
    String deleteUrl = "files/dir/%s/delete";

    static String downurl = "/v2/files/%s/download ";
    final String delUrl = String.format(deleteUrl, "b686b660-6ca8-4ad9-9e7f-7137615e2a1b");

    public void useAppContext() throws Exception {
        // Context of the app under test.

        File file = new File("/sdcard/abcc.tar");
        Map<String, String> params = new HashMap<>();
        params.put("fileName ", "test.xz");
        params.put("createUser ", "66661");
        params.put("parentId  ", "66661");
        params.put("createUser ", "66661");

        uploadFile(file, baseUrl + uploadUrl, params, new ProgressListener() {
            @Override
            public void onProgress(long totalBytes, long remainingBytes, boolean done) {
                Log.e(TAG, "onProgress: total " + totalBytes + " remain: " + remainingBytes + " is done " + done);
            }
        });
    }


    public void downloadFile() {
        Log.e(TAG, "downloadFile: ");
        String format = String.format(downurl, "6e5c8d28-d8ba-4be9-be71-8d886a19561e");
        String url = baseUrl + format;
        OkHttpClient okHttpClient = new OkHttpClient();

        FormBody.Builder builder = new FormBody.Builder();
        builder.add("fileid", "6e5c8d28-d8ba-4be9-be71-8d886a19561e");
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                parse(response);
            }
        });

    }

    private void parse(Response response) throws IOException {
        InputStream inputStream = response.body().byteStream();

        File file = new File("/sdcard/haha");
        if (!file.exists()) {
            file.mkdir();
        }

        File file1 = new File(file, "aa.jpg");
        FileOutputStream fileOutputStream = new FileOutputStream(file1);
        int len = 0;
        byte[] b = new byte[1024];
        int total = 0;
        while (-1 != (len = inputStream.read(b))) {
            fileOutputStream.write(b, 0, len);
            total += len;
            Log.e(TAG, "size : 55971   current: " + total);
        }
        fileOutputStream.flush();
        fileOutputStream.close();
    }

    /**
     * 上传文件
     *
     * @param fileData   文件二进制流
     * @param fileName   文件名称，标明文件格式
     * @param createUser 文件拥有者
     * @param parentId   文件所在的目录
     * @param success    返回请求成功的block
     * @param failure    返回请求失败的block
     */
    private static void uploadFile(File file, String uploadPath, Map<String, String> params, ProgressListener listener) {

        if (file == null || !file.exists()) {
            throw new RuntimeException("文件不存在");
        }

        OkHttpClient okHttpClient = new OkHttpClient();
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);


        RequestBody customRequestBody = createCustomRequestBody(MultipartBody.FORM ,file, listener);
        builder.addFormDataPart("file", file.getName(), customRequestBody);
        if (params != null) {

            Set<Map.Entry<String, String>> entries = params.entrySet();
            Iterator<Map.Entry<String, String>> iterator = entries.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> next = iterator.next();
                builder.addFormDataPart(next.getKey(), next.getValue());
            }
        }

        RequestBody requestBody = builder.build();

        Request request = new Request.Builder()
                .url(uploadPath) //地址
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {


                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e(TAG, "onResponse: "  );
            }
        });
    }

    public static RequestBody createCustomRequestBody(final MediaType contentType, final File file, final ProgressListener listener) {
        return new RequestBody() {
            @Override
            public MediaType contentType() {
                return contentType;
            }

            @Override
            public long contentLength() {
                return file.length();
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                Source source;
                try {
                    source = Okio.source(file);
                    //sink.writeAll(source);
                    Buffer buf = new Buffer();
                    Long remaining = contentLength();
                    for (long readCount; (readCount = source.read(buf, 2048)) != -1; ) {
                        sink.write(buf, readCount);
                        listener.onProgress(contentLength(), remaining -= readCount, remaining == 0);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }

    interface ProgressListener {
        void onProgress(long totalBytes, long remainingBytes, boolean done);
    }


}
